import { addItemToCart, fetchCartInfo, modifyCartItemNum, modifyCartItemSelected, removeCartItem } from '@/api'
import { Toast } from 'antd-mobile';
export default {
  // 命名空间
  namespace: 'cart',
  state: {
    // 购物车中数据
    items: [],
    // 购物车所有选中商品的总价格
    total: 0,
    // 购物车中所有商品的总件数
    number: 0
  },
  reducers: {
    // 给购物车数据赋值
    initCart(state: any, action: any) {
      state.items = action.data.items;
      state.total = action.data.price;
      state.number = action.data.number
      return {
        ...state
      }
    },

  },
  // 处理异步
  effects: {
    // 加入购物车
    *addItem(action: any, { put, call }: any) {
      // action.data {goodsId: xxx, number: 111}
      const res = yield call(addItemToCart, action.data);
      if (res.data.code === 0) {
        Toast.show({ content: '加入购物车成功' })
        yield put({ type: 'initCart', data: res.data.data });
      }
    },
    // 读取购物车数据
    *fetchItemInfo(action: any, { put, call }: any) {
      // 调用请求
      const res = yield call(fetchCartInfo);
      // 触发reducer
      if (res.data.code === 0) {
        yield put({ type: 'initCart', data: res.data.data });
      }
    },
    // 修改购物车商品购买数量
    *modifyItemNum(action: any, { put, call }: any) {
      // 调用请求 action.data {key, number}
      const res = yield call(modifyCartItemNum, action.data);
      // 触发reducer
      if (res.data.code === 0) {
        Toast.show({ content: '修改成功' })
        yield put({ type: 'initCart', data: res.data.data });
      }
    },
    // 修改购物车商品选中状态
    *modifyItemSelected(action: any, { put, call }: any) {
      // 调用请求 action.data {key, selected}
      const res = yield call(modifyCartItemSelected, action.data);
      // 触发reducer
      if (res.data.code === 0) {
        Toast.show({ content: '修改成功' })
        yield put({ type: 'initCart', data: res.data.data });
      }
    },
    // 删除购物车商品
    *removeItem(action: any, { put, call }: any) {
      // 调用请求 action.data {key}
      const res = yield call(removeCartItem, action.data);
      // 触发reducer
      if (res.data.code === 0) {
        Toast.show({ content: '删除成功' })
        yield put({ type: 'initCart', data: res.data.data });
      }
      if (res.data.code === 700) {
        yield put({
          type: 'initCart', data: {
            items: [],
            price: 0,
            number: 0
          }
        });
      }
    }
  },
};
